package com.lin.nio.channel.aio;

import com.lin.nio.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;

/**
 * AsynchronousFileChannel 一个用于读取、写入和操作文件的异步通道
 */
@Slf4j
public class AioFileChannel {
    public static void main(String[] args) {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("E:\\ljl\\net-programme\\src\\main\\resources\\data-out.txt"))) {


            ByteBuffer dst = ByteBuffer.allocate(16);
            log.debug("read before...");

            /**
             * 写入的缓冲区
             * 文件起始读取位置
             * 附件
             * 异步回调对象
             */
            channel.read(dst, 0, dst, new CompletionHandler<Integer, ByteBuffer>() {
                /**
                 * 这是守护线程，主线程执行完毕，守护线程会自动退出
                 * @param result
                 * @param attachment
                 */
                @Override
                public void completed(Integer result, ByteBuffer attachment) { // 读取成功调用
                    log.debug("read completed...");
                    String s = ByteBufferUtil.debugAll(attachment);
                    System.out.println(s);
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) { // 读取失败调用

                }
            });
            log.debug("finish...");
            System.in.read();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
